package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.dto.QueryDeviceDataListDto;
import com.zzyl.serve.dto.UserLoginRequestDto;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.service.WechatService;
import com.zzyl.serve.vo.DeviceDataGraphVo;
import com.zzyl.serve.vo.LoginVo;
import com.zzyl.serve.vo.WeekDateVo;
import org.apache.ibatis.annotations.Param;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.FamilyMemberMapper;
import com.zzyl.serve.domain.FamilyMember;
import com.zzyl.serve.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 *
 * @author itheima
 * @date 2025-03-12
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }




    @Autowired
    private WechatService webschatService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ElderServiceImpl elderService;
    @Autowired
    private FamilyMemberServiceImpl familyMemberService;

    /**
     * 小程序端 用户登录的逻辑处理
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {


        //1.根据code调用微信api获取apenId
        String openid = webschatService.getOpenid(dto.getCode());

        //2.根据openId查询数据库获取用户信息family_member表
        FamilyMember familyMember = getOne(
                new LambdaQueryWrapper<FamilyMember>()
                        .eq(FamilyMember::getOpenId, openid)
        );

        //3.调用微信api获取用户绑定手机号
        String phone = webschatService.getPhone(dto.getPhoneCode());


        //4.判断用户信息是否存在，如果不存在，则新增family_member表
        //5.存在则 修改family_member表数据
        if (ObjectUtil.isNull(familyMember)) {
            // 新用户


            familyMember = new FamilyMember();
            familyMember.setPhone(phone);
            familyMember.setOpenId(openid);

            // 设置初始随机名称
            familyMember.setName("花开富贵" + DateUtils.getTime());

            save(familyMember);

        } else {
            // 老用户
            familyMember.setPhone(phone);
            updateById(familyMember);
        }


        //6.将用户id存入token中，并返回数据给前端
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());
        return loginVo;
    }

    @Override
    public List<WeekDateVo> queryDeviceDataListByWeek(String iotId, String functionId, Long startTime, Long endTime) {
        List<WeekDateVo> list = familyMemberMapper.queryDeviceDataListByWeek(
                iotId,
                functionId,
                LocalDateTimeUtil.of(startTime),
                LocalDateTimeUtil.of(endTime));

        return list;
    }
//67d3bbec375e694aa6926ffd_yd001   BedExitCount
    @Override
    public List<DeviceDataGraphVo> queryDeviceDataListByDay(QueryDeviceDataListDto dto) {
        Long start = dto.getStartTime();
        Long end = dto.getEndTime();
        Instant instant = Instant.ofEpochMilli(start);
        // 将 Instant 转换为 LocalDateTime（使用东八区时区）
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Asia/Shanghai"));
        LocalDateTime startTime = zonedDateTime.toLocalDateTime();
        Instant instant1 = Instant.ofEpochMilli(end);
        ZonedDateTime zonedDateTime1 = instant1.atZone(ZoneId.of("Asia/Shanghai"));
        LocalDateTime endTime = zonedDateTime1.toLocalDateTime();
        List<DeviceDataGraphVo> DataList= deviceDataMapper.queryDeviceDataListByDay(dto.getFunctionId(), startTime, endTime, dto.getIotId());
        return DataList;

    }

   /* @Override
    public List<DeviceDataGraphVo> queryDeviceDataListByDay(QueryDeviceDataListDto dto) {
        //创建dataListVo对象

        //创建一个List<DataListVo>来存储转换后的对象
        List<DeviceDataGraphVo> dataListVoList = new ArrayList<>();
        //dto的时间戳需要转换成LocalDateTime
        Long start = dto.getStartTime();
        System.out.println(start);
        Long end = dto.getEndTime();
        System.out.println(end);
        Instant instant = Instant.ofEpochMilli(start);
        System.out.println(instant);
        // 将 Instant 转换为 LocalDateTime（使用东八区时区）
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Asia/Shanghai"));
        LocalDateTime startTime = zonedDateTime.toLocalDateTime();
        System.out.println(startTime);
        Instant instant1 = Instant.ofEpochMilli(end);
        System.out.println(instant1);
        ZonedDateTime zonedDateTime1 = instant1.atZone(ZoneId.of("Asia/Shanghai"));
        LocalDateTime endTime = zonedDateTime1.toLocalDateTime();
        System.out.println(endTime);

        //调用deviceDataMapper的查询方法
        List<DeviceDataGraphVo> deviceDataList = deviceDataMapper.queryDeviceDataListByDay(dto.getFunctionId(), startTime, endTime, dto.getIotId());
//        for (DeviceData deviceData : deviceDataList) {
//            DataListVo dataListVo = new DataListVo();
//            dataListVo.setDateTime(String.valueOf(deviceData.getAlarmTime()));
//            dataListVo.setDataValue(deviceData.getDataValue());
//            dataListVoList.add(dataListVo);
//        }
        deviceDataList.forEach(deviceData -> {
            System.out.println(deviceData.getDateTime());
        });

        return deviceDataList;

    }*/



    /*@Override
    public QueryDeviceDataListVo queryDeviceDataListByDay(String functionId, Long startTime, Long endTime, String iotId) {
        // 判断 dto 的设备 ID 是否为空
        if (ObjectUtil.isEmpty(iotId)) {
            throw new RuntimeException("没有查到此设备");
        }
        Instant instant = Instant.ofEpochMilli(startTime);
        // 将 Instant 转换为 LocalDateTime（使用东八区时区）
        LocalDateTime startTime1 = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Shanghai"));
        Instant instant1 = Instant.ofEpochMilli(endTime);
        LocalDateTime endTime1 = LocalDateTime.ofInstant(instant1, ZoneId.of("Asia/Shanghai"));
        // 构建查询条件
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<DeviceData>()
                .eq(DeviceData::getIotId, iotId)
                .eq(DeviceData::getFunctionId,functionId)
                .ge(DeviceData::getAlarmTime, startTime1)
                .le(DeviceData::getAlarmTime, endTime1)
                .orderByDesc(DeviceData::getAlarmTime);

        // 使用 deviceDataMapper 查询 DeviceData 表的数据
        List<DeviceData> deviceDataList = deviceDataMapper.selectList(queryWrapper);

        // 创建一个 List<DataListVo> 来存储转换后的对象
        List<DataListVo> dataListVoList = new ArrayList<>();

        // 遍历 deviceDataList 并转换为 DataListVo
        deviceDataList.forEach(deviceData -> {
            DataListVo dataListVo = new DataListVo();
            // 设置完整的日期和时间信息
            dataListVo.setDateTime(deviceData.getAlarmTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")));
            dataListVo.setDataValue(deviceData.getDataValue());
            dataListVoList.add(dataListVo);
        });

        // 创建 QueryDeviceDataListVo 对象
        QueryDeviceDataListVo queryDeviceDataListVo = new QueryDeviceDataListVo();
        queryDeviceDataListVo.setDataList(dataListVoList);
        // 设置 operationTime 为当前时间
        queryDeviceDataListVo.setOperateTime(LocalDateTime.now());

        return queryDeviceDataListVo;
    }*/

    @Autowired
    private DeviceDataMapper deviceDataMapper;
    /*@Override
    public QueryDeviceDataListVo queryDeviceDataListByDay(QueryDeviceDataListDto dto) {
        //判断dto的设备ID是否为空，为空则返回空集合
        if(ObjectUtil.isEmpty(dto.getIotId())){
            throw new RuntimeException("没有查到此设备");
        }
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<DeviceData>()
                .eq(DeviceData::getIotId, dto.getIotId())
                .eq(DeviceData::getFunctionId, dto.getFunctionId())
                .ge(DeviceData::getAlarmTime, dto.getStartTime())
                .le(DeviceData::getAlarmTime, dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime);
        List<DeviceData> deviceDataList = deviceDataMapper.selectList(queryWrapper);
        //遍历设备数据集合
        List<DataListVo> dataListVoList = new ArrayList<>();
        deviceDataList.forEach(deviceData -> {
            DataListVo dataListVo = new DataListVo();
            dataListVo.setDateTime(deviceData.getAlarmTime().toString());
            dataListVo.setDataValue(deviceData.getDataValue());
            dataListVoList.add(dataListVo);
        });
        QueryDeviceDataListVo queryDeviceDataListVo = new QueryDeviceDataListVo();
        queryDeviceDataListVo.setDataList(dataListVoList);
        queryDeviceDataListVo.setOperateTime(LocalDateTime.now());
        return queryDeviceDataListVo;


    }*/
   /* @Override
    public QueryDeviceDataListVo queryDeviceDataListByDay(functionId, startTime, endTime, iotId) {
        // 判断 dto 的设备 ID 是否为空
        if (ObjectUtil.isEmpty(dto.getIotId())) {
            throw new RuntimeException("没有查到此设备");
        }

        Instant instant = Instant.ofEpochMilli(dto.getStartTime());
        // 将 Instant 转换为 LocalDateTime（使用东八区时区）
        LocalDateTime startTime = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Shanghai"));
        Instant instant1 = Instant.ofEpochMilli(dto.getEndTime());
        LocalDateTime endTime = LocalDateTime.ofInstant(instant1, ZoneId.of("Asia/Shanghai"));
        // 构建查询条件
        LambdaQueryWrapper<DeviceData> queryWrapper = new LambdaQueryWrapper<DeviceData>()
                .eq(DeviceData::getIotId, dto.getIotId())
                .eq(DeviceData::getFunctionId, dto.getFunctionId())
                .ge(DeviceData::getAlarmTime, startTime)
                .le(DeviceData::getAlarmTime, endTime)
                .orderByDesc(DeviceData::getAlarmTime);

        // 使用 deviceDataMapper 查询 DeviceData 表的数据
        List<DeviceData> deviceDataList = deviceDataMapper.selectList(queryWrapper);

        // 创建一个 List<DataListVo> 来存储转换后的对象
        List<DataListVo> dataListVoList = new ArrayList<>();

        // 遍历 deviceDataList 并转换为 DataListVo
        deviceDataList.forEach(deviceData -> {
            DataListVo dataListVo = new DataListVo();
            // 设置完整的日期和时间信息
            dataListVo.setDateTime(deviceData.getAlarmTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")));
            dataListVo.setDataValue(deviceData.getDataValue());
            dataListVoList.add(dataListVo);
        });

        // 创建 QueryDeviceDataListVo 对象
        QueryDeviceDataListVo queryDeviceDataListVo = new QueryDeviceDataListVo();
        queryDeviceDataListVo.setDataList(dataListVoList);
        // 设置 operationTime 为当前时间
        queryDeviceDataListVo.setOperateTime(LocalDateTime.now());

        return queryDeviceDataListVo;
    }*/



}
